package com.chuangfeng.framework.core.common.struts2.action;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.Validateable;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.ValidationAwareSupport;


/**
 * **********************************************************************************
 * 整个架构中以struts2.2为控制层，这是所有ACTION类的祖先类，该类继承ActionSupport，具备了Struts2
 * 中的控制层；同时具备了Validateable,ValidationAware的框架校验能力；同时继承了Preparable接口来
 * 自动初始化Request,Response,Session,ServletContext等对象。
 * ***********************************************************************************
 * 
 * @author xiedy
 *
 */
public class BaseAction  implements Preparable,Action, Validateable,ValidationAware {

	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(BaseAction.class);
	private final ValidationAwareSupport validationAware = new ValidationAwareSupport();
	
	/*
	 * 定位导向
	 */
	public static final String LIST = "list";
	public static final String EDIT = "edit";
	public static final String ADD = "add";
	public static final String DEL = "del";
	public static final String UPDATE = "update";
	public static final String SELECT = "select";
	public static final String QUERY = "query";
	public static final String LEFT = "left";
	public static final String RIGHT = "right";
	public static final String INDEX = "index";
	public static final String MAIN = "main";
	public static final String MESSAGE = "message";
	public static final String JSONOBJECT = "jsonObject";
	public static final String JSONTEXT = "jsonText";
	
	/*
	 * 针对JSON串
	 */
	protected Object jsonObject;
	protected String jsonText;
	
    /*
     *页面主流的几大对象 
     */
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected ServletContext application;
	
	
	/**
	 * 通过preparableInterceptor拦截器拦截，自动加载Action，通过prepare()方法初始化属性
	 */
	public void prepare() throws Exception {
    
		log.debug("现在开始初始化(request、response、session、application)：");
		try{
			request = ServletActionContext.getRequest();
			response = ServletActionContext.getResponse();
			session = request.getSession();		
			application = ServletActionContext.getServletContext();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		log.debug("结束初始化：");
	}
	
	/**
	 * 判断浏览是否为firefox
	 */
	public boolean isFF(){
        String agent = request.getHeader("USER-AGENT");
        if(agent == null){
        	return false;
        }
        return -1 != agent.indexOf("Firefox");
	}
	
	/**
	 * 获取当前登录的用户IP
	 * @return 当前登录用户的IP地址
	 */
	protected String getLoginIp(){
		return request.getRemoteAddr();		
	}
	
	/**
	 * 设置列表页面每页显示的数目
	 */
	protected void setPageSize(int ps){
		request.setAttribute("pagesize", ps);
	}
	
	
	/**
	 * 获取cookie名称
	 * @param key cookie名称
	 * @return cookie的值
	 */
	public String getCookie(String key){
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies){
				if (cookie.getName().equals(key))
					return cookie.getValue();
			}
		}
		return "";
	}
	
	
	/**
	 * 设置cookie值，默认cookie的有效时间为一年（365天）
	 * @param key cookie名称
	 * @param value cookie值
	 */
	public void setCookie(String key, String value){
		this.setCookie(3600*24*365, key, value);
	}
	
	/**
	 * 设置cookie值
	 * @param times 精确到秒
	 * @param key cookie名称
	 * @param value cookie值
	 */
	public void setCookie(int times,String key,String value){
		Cookie cookie = new Cookie(key, value);
		if(times==0){
			cookie.setMaxAge(3600*24*365); //默认保存一年
		}else{
			cookie.setMaxAge(times);
		}
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	/**删除cookie
	 * @param key cookie名称
	 */
	public void delCookie(String key){
		try{
			Cookie[] cookies = request.getCookies();
			if(cookies==null)
				return;
			for (Cookie cookie : cookies){
				if (cookie.getName().equals(key)){
					cookie.setMaxAge(0);
					response.addCookie(cookie);				
					return;
				}
			}
		}catch (Exception e) {
			log.info("删除cookies异常,"+"key:"+key);
			log.info(e.getMessage());
		}
	}
	
	/**
	 * 处理校验错误信息
	 */
	public void setActionErrors(Collection errorMessages) {
		validationAware.setActionErrors(errorMessages);
	}

	public Collection getActionErrors() {
		return validationAware.getActionErrors();
	}

	public void setActionMessages(Collection messages) {
		validationAware.setActionMessages(messages);
	}

	public Collection getActionMessages() {
		return validationAware.getActionMessages();
	}

	public void setFieldErrors(Map errorMap) {
		validationAware.setFieldErrors(errorMap);
	}

	public Map getFieldErrors() {
		return validationAware.getFieldErrors();
	}

	public boolean hasActionErrors() {
		return validationAware.hasActionErrors();
	}

	public boolean hasActionMessages() {
		return validationAware.hasActionMessages();
	}

	public boolean hasErrors() {
		return validationAware.hasErrors();
	}

	public boolean hasFieldErrors() {
		return validationAware.hasFieldErrors();
	}

	public void addActionError(String anErrorMessage) {
		validationAware.addActionError(anErrorMessage);
	}

	public void addActionMessage(String aMessage) {
		validationAware.addActionMessage(aMessage);
	}

	public void addFieldError(String fieldName, String errorMessage) {
		validationAware.addFieldError(fieldName, errorMessage);
	}

	public void validate() {
	}
	
	/**处理校验错误信息end ***/
	 
	
	

	public Object getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(Object jsonObject) {
		this.jsonObject = jsonObject;
	}

	public String getJsonText() {
		return jsonText;
	}

	public void setJsonText(String jsonText) {
		this.jsonText = jsonText;
	}

	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	

}
